//LazySingleton2.java
package singletonAndMultiton;

/**
 * expect: synchronize at first time.
 * but it will result in a serious error
 *@author:youtubezou
 *@version:2012-7-13
 */
public class LazySingleton2 {
	static{
		System.out.println("start initialize");
	}
	private static LazySingleton2 m_instance = null;
	private static LazySingleton2 m_instance2 = new LazySingleton2();
	
	static{
		System.out.println("end initialize");
	}

	
	private LazySingleton2() {
		System.out.println("create instance");
	}
	
	public static LazySingleton2 getInstance(){
		//threads check instance exist or not
		if (m_instance == null){
			//block threads,which try to create instance
			synchronized(LazySingleton2.class){
				//allow only one thread enter at a time
				if (m_instance == null){
					m_instance = new LazySingleton2();
					/**
					 * there is a problem.we can't ensure java-complier assign the address
					 * to m_instance after the object has been initialized.
					 * if not, other threads will get a uninitialized object to use, which
					 * may break the program.
					 * <h3>Eg:pseudo</h3><br><blockquote>
					 * 	mem = allocate();            //Allocate memory for Singleton object.
					 *	instance = mem;             //Note that instance is now non-null, but
                     *        						//has not been initialized.
					 *	LazySingleton2(instance);   //Invoke constructor for Singleton passing
					 *</blockquote>
					 */
				}
			}
		}
		
		return m_instance;
	}
	
	public static LazySingleton2 getInstance2(){
		return m_instance2;
	}
	
	public String toString(){
		return "double check lazy singleton pattern";
	}

}
